﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;

namespace YAGMRC.Core.Commands
{
    public class GetGamesAndPlayersCommand : ICommand, IResult<YAGMRC.Core.Models.GetGamesAndPlayers.GetGamesAndPlayersCommandResult>
    {
        #region Constructor

        private GetGamesAndPlayersCommand()
        {
        }

        internal GetGamesAndPlayersCommand(Resolver resolver)
        {
            m_Resolver = resolver;
        }

        #endregion Constructor

        private Resolver m_Resolver;

        private List<long> GetPlayerIDs(YAGMRC.Core.Models.GetGamesForPlayer.GetGamesForPlayerCommandResult getGamesPlayer)
        {
            List<long> playerIDList = new List<long>();

            foreach (var result in getGamesPlayer.Result)
            {
                foreach (var player in result.Players)
                {
                    if (!playerIDList.Contains(player.UserId))
                    {
                        playerIDList.Add(player.UserId);
                    }
                }
            }

            return playerIDList;
        }

        public void Execute()
        {
            if (!this.CanExecute())
            {
                this.Result = new YAGMRC.Core.Models.GetGamesAndPlayers.GetGamesAndPlayersCommandResult(new YAGMRC.Core.Models.GetGamesAndPlayers.RootObject());
                return;
            }

            AuthenticateCommandResult auth = m_Resolver.Get<AuthenticateCommandResult>();
            YAGMRC.Core.Models.GetGamesForPlayer.GetGamesForPlayerCommandResult getGamesPlayer = m_Resolver.Get<YAGMRC.Core.Models.GetGamesForPlayer.GetGamesForPlayerCommandResult>();

            Trace.Assert(getGamesPlayer.HasResult);

            List<long> players = this.GetPlayerIDs(getGamesPlayer);

            string playerIDText = string.Join("_", players.ConvertAll<string>((long playerID) => playerID.ToString()));

            WebDownload executeWeb = m_Resolver.Get<WebDownload>();
            this.Result = new Models.GetGamesAndPlayers.GetGamesAndPlayersCommandResult(executeWeb.Execute<YAGMRC.Core.Models.GetGamesAndPlayers.RootObject>("GetGamesAndPlayers?playerIDText=" + playerIDText + "&authKey=" + auth.AuthID));
        }

        public YAGMRC.Core.Models.GetGamesAndPlayers.GetGamesAndPlayersCommandResult Result
        {
            get;
            private set;
        }

        public bool CanExecute()
        {
            AuthenticateCommandResult auth = m_Resolver.Get<AuthenticateCommandResult>();
            if ((null != auth) && (auth.Authenticated))
            {
                return true;
            }

            return false;
        }
    }
}